<template>
	<view class="container">
		<!-- 视频播放器 -->
		<view class="video-container">
			<video id="videoRef" ref="videoRef" :src="processVideoUrl(videoDetail.video)" :poster="videoDetail.cover"
				class="video-player" controls @error="handleVideoError" @timeupdate="onVideoTimeUpdate"
				@play="onVideoPlay" @ended="onVideoEnded"></video>
		</view>

		<!-- 指导视频信息 -->
		<view class="video-info">
			<view class="title">{{videoDetail.name}}</view>
			<view class="meta">
<!-- 				<view class="tutor">
					<u-icon name="account" size="28" color="#666"></u-icon>
					<text>{{videoDetail.tutor}}</text>
				</view> -->
				<view class="duration">
					<u-icon name="clock" size="28" color="#666"></u-icon>
					<text>{{formatDuration(videoDetail.duration)}}</text>
				</view>
				<view class="views">
					<u-icon name="eye" size="28" color="#666"></u-icon>
					<text>{{counts}}次观看</text>
				</view>
			</view>
		</view>

		<!-- 视频简介 -->
		<!-- <view class="detail-section">
			<view class="section-title">视频简介</view>
			<view class="description">{{videoDetail.introduction}}</view>
		</view> -->

		<!-- 视频大纲 -->
<!-- 		<view class="outline-section">
			<view class="section-title">视频大纲</view>
			<view class="outline-list">
				<view class="chapter">第{{videoDetail.videoOrder}}节：{{videoDetail.name}}</view>
				<view class="duration">时长：{{formatDuration(videoDetail.duration)}}</view>
			</view>
		</view> -->
	</view>
</template>

<script>
	import {
		getGuidanceVideoById
	} from '../../common/api'
	import {
		getStrokeUserInfo,
		addVideoHistory,
		updateVideoHistory,
		getVideoHistoryById
	} from '../../common/api'

	export default {
		data() {
			return {
				showCustomTabBar: true,
				videoDetail: {},
				currentProgress: 0,
				counts: 0,
				userId: 0,
				guidanceId: 0,
				videoHistory: {},
				hasSeeked: false,
				hasPlayedThisRound: false
			}
		},
		onShow() {},
		onLoad(options) {
			// 获取指导视频ID
			const videoId = options.id;

			// 串行执行异步操作，确保顺序
			this.getUserId()
				.then(() => this.loadGuidanceVideoById(videoId))
				.then(() => this.loadCurrentVideoHistory())

				.catch(error => {
					console.error('初始化失败:', error);
				});
		},
		onUnload() {
			// 页面退出时提交一次观看进度
			this.submitVideoHistoryOnExit();
		},
		methods: {
			processVideoUrl(url) {
				if (!url) return '';
				// 检查是否以"http:"开头但缺少第二个斜杠
				if (url.startsWith('http:/') && !url.startsWith('http://')) {
					return url.replace('http:/', 'http://');
				}
				return url;
			},
			async onVideoTimeUpdate(e) {

				this.currentProgress = e.detail.currentTime;
			},
			onVideoEnded() {
				console.log('当前hasPlayedThisRound：', this.hasPlayedThisRound)
				if (!this.hasPlayedThisRound) {
					this.counts += 1;
					this.hasPlayedThisRound = true;
				}
				console.log('当前counts：', this.counts)
				// 回到视频开头
				const videoContext = uni.createVideoContext('videoRef', this);
				videoContext.seek(0);
			},
			onVideoPlay() {
				// 如果是“已看完”状态，直接seek到0
				if (this.hasPlayedThisRound) {
					const videoContext = uni.createVideoContext('videoRef', this);
					videoContext.seek(0);
					this.hasPlayedThisRound = false; // 新一轮播放
					this.hasSeeked = true;
					return;
				}
				if (!this.hasSeeked && this.videoHistory.currentProgress) {
					const videoContext = uni.createVideoContext('videoRef', this);
					videoContext.seek(this.videoHistory.currentProgress);
					this.hasSeeked = true;
				}
			},


			async loadGuidanceVideoById(id) {
				try {
					const qlRes = await getGuidanceVideoById(id);
					this.videoDetail = qlRes.data || {};
					console.log('根据id查到的视频：', this.videoDetail);
					this.guidanceId = this.videoDetail.id || 0;
				} catch (e) {
					console.error('加载指导视频失败', e);
				}
			},
			handleVideoError(event) {
				console.error('视频加载错误:', event);
				this.showVideoError = true;
			},
			async getUserId() {
				try {
					const res = await getStrokeUserInfo();
					this.userId = res.data.userId || 0;
					console.log('用户ID:', this.userId);
				} catch (e) {
					console.error('获取用户信息失败', e);
				}
			},
			formatDuration(seconds) {
				if (seconds === undefined || seconds === null) return '0分0秒';
				const min = Math.floor(seconds / 60);
				const sec = seconds % 60;
				return `${min}分${sec.toFixed(0)}秒`;
			},
			async loadCurrentVideoHistory() {
				// 确保userId和guidanceId已加载
				if (!this.userId || !this.guidanceId) {
					console.error('用户ID或视频ID未定义，无法加载视频历史');
					return;
				}

				try {
					console.log('guidanceId：', this.guidanceId);
					const qlRes = await getVideoHistoryById({
						params: {
							userId: this.userId,
							guidanceId: this.guidanceId
						}
					});
					console.log('根据id查到的视频记录：', qlRes);

					if (qlRes.rows && qlRes.rows.length > 0) {
						this.videoHistory = qlRes.rows[0];
						this.counts = this.videoHistory.counts || 0;
						// 判断是否已播放完成
						if (
							this.videoHistory.currentProgress &&
							this.videoDetail.duration &&
							Math.abs(this.videoHistory.currentProgress - this.videoDetail.duration) < 1 // 容差1秒
						) {
							// 已经播放完成，重置进度
							this.$nextTick(() => {
								const videoContext = uni.createVideoContext('videoRef', this);
								videoContext.seek(0);
							});
							this.currentProgress = 0;
							this.hasSeeked = true;
							this.hasPlayedThisRound = true; // 本轮不再计数
						} else {
							this.hasSeeked = false;
							this.hasPlayedThisRound = false;
						}
					} else {
						this.videoHistory = {};
						this.counts = 0;
						this.hasPlayedThisRound = false;
					}
				} catch (e) {
					console.error('加载指导视频记录失败', e);
					this.videoHistory = {};
				}
			},
			async submitVideoHistoryOnExit() {
				console.log('提交观看历史记录');

				// 防御性编程：确保必要数据存在
				if (!this.userId || !this.guidanceId || !this.videoDetail.duration) {
					console.error('关键数据缺失，无法提交观看记录');
					return;
				}
				const guidanceStatus = this.counts > 0 ? 1 : 0;
				if (this.videoHistory.id) {
					// 更新已有记录
					try {
						const res = await updateVideoHistory({
							id: this.videoHistory.id,
							userId: this.userId,
							guidanceId: this.guidanceId,

							currentProgress: this.currentProgress,
							guidanceStatus: guidanceStatus,
							counts: this.counts
						});
						console.log('后端存储成功，返回数据:', res);
					} catch (e) {
						console.error('存储指导视频历史失败:', e);
					}
				} else {
					// 新增记录（如有需要）
					try {
						const res = await addVideoHistory({
							userId: this.userId,
							guidanceId: this.guidanceId,
							currentProgress: this.currentProgress,
							guidanceStatus: guidanceStatus,
							counts: this.counts
						});
						console.log('后端存储成功，返回数据:', res);
					} catch (e) {
						console.error('存储指导视频历史失败:', e);
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0;
		background: #f5f5f5;
	}

	.video-container {
		width: 100%;
		height: 422rpx;
		background: #000;

		.video-player {
			width: 100%;
			height: 100%;
		}
	}

	.video-info {
		background: #fff;
		padding: 30rpx;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}

		.meta {
			display: flex;
			align-items: center;
			gap: 30rpx;

			.tutor,
			.duration,
			.views {
				display: flex;
				align-items: center;
				font-size: 24rpx;
				color: #666;

				text {
					margin-left: 8rpx;
				}
			}
		}
	}

	.detail-section,
	.outline-section {
		margin-top: 20rpx;
		background: #fff;
		padding: 30rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}

		.description {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
		}
	}

	.outline-list {
		.outline-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #eee;

			&:last-child {
				border-bottom: none;
			}

			.chapter {
				font-size: 28rpx;
				color: #333;
			}

			.duration {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
</style>